package com.lianqi.emcpframework.data.masker.stratgey;

import java.util.List;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import com.lianqi.emcpframework.data.masker.annotation.MaskData;
import com.lianqi.emcpframework.utils.StringUtils;

/**
 * @program emcp-framework
 * @ClassName StringMaskStrategy
 * @description: 字符串脱敏策略类
 * @author: sky
 * @create: 2019/05/26 18:39
 */
public abstract class StringMaskStrategy implements DataMaskStrategy<String> {

    @Override
    public String maskValue(Object value, MaskData maskData) {
        if (StringUtils.isNullOrEmpty(value)) {
            return null;
        }
        int maskleft = defaultMaskLeft();
        int maskright = defaultMaskRight();
        String maskChar = DEFAULT_MASK_CHAR;
        if (maskData != null) {
            if (!"".equals(maskData.expression())) {
                ExpressionParser parser = new SpelExpressionParser();
                List<Integer> list = (List<Integer>)parser.parseExpression(maskData.expression()).getValue();
                maskleft = list.get(0);
                maskright = list.get(1);
            }
            maskChar = maskData.maskCharacter();
        }
        String oldValue = value.toString();

        int maskLength = oldValue.length() - maskleft - maskright;
        String maskStr = "";
        if (maskLength > 0) {
            for (int i = 0; i < maskLength; i++) {
                maskStr = maskStr.concat(maskChar);
            }
        }
        String newValue = org.apache.commons.lang3.StringUtils.left(oldValue, maskleft).concat(maskStr)
            .concat(org.apache.commons.lang3.StringUtils.right(oldValue, maskright));
        return newValue;
    }

}
